#能用来分析 豆瓣(www.douban.com)  上的二手书信息
use strict;
use LWP::Simple;
use HTML::TreeBuilder;
use Encode;

binmode(STDIN, ':encoding(utf8)');
binmode(STDOUT, ':encoding(gb2312)');
binmode(STDERR, ':encoding(gb2312)');

my $url = "http://book.douban.com/subject/1231590/";
my $content = get($url);
#print $content;
my $tree = HTML::TreeBuilder->new();

$tree->parse( $content );

#*********  分析书名
#直接分析title时，书名后面会有"(豆瓣)"(且是乱码，暂时没能用字符串替换的方法解决)，所以分析"<h1>Effective C++中文版</h1>"标签
my $book_name_node = $tree->look_down('_tag','h1');
if( $book_name_node ){
	my $book_name = $book_name_node->as_text;
	print $book_name,"\n";
}

#*********  分析书的评分指数 
my $score_node = $tree->look_down('class','ll rating_num');
if( $score_node ){
	print "score(0-10) : ",$score_node->as_text,"\n";
}

#*********  分析二手书转让的链接.
#逐层查找到二手转让的地址: class=aisde ==> class=indent ==> <a href="...(这就是所需要的地址)">
my $secondhand_root = $tree->look_down('class', 'aside');  
my $secondhand_link_node;
my $secondhand_link;
if( $secondhand_root ) {
	my $indent = $secondhand_root->look_down('class','indent');
      	if( $indent ){
      		$secondhand_link_node  = $indent->look_down('_tag','a');
	}
} 

if( defined($secondhand_link_node) ){
	$secondhand_link = $secondhand_link_node->attr('href');
      	print "link : ",$secondhand_link,"\n";
}else{
	die "Can't get the secondhand link.";
}

$tree->delete;

#*********  根据二手书转让的链接分析卖书的信息
my $secondhand_content = get($secondhand_link);

my $secondhand_tree = HTML::TreeBuilder->new();
$secondhand_tree->parse( $secondhand_content );

my $article = $secondhand_tree->look_down('class','article'); 
my @sellers;
if( $article ){
	@sellers = $article->look_down('_tag','table');
}
if( @sellers){
	shift @sellers;
	foreach my $seller (@sellers){
		my @info = $seller->look_down('_tag','td');
		if( @info ){
			my $node = pop @info;
			my $link_node = $node->look_down('_tag','a');
			print "seller's link: ","http://book.douban.com".($link_node->attr('href')),"\n";
			foreach my $info_text (@info){
				print $info_text->as_text," ";
			}
			print "\n";
		}	
	}
}

$secondhand_tree->delete;
